package cn.com.utt.unms.service.impl;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import cn.com.utt.common.mapper.UserMapper;
import cn.com.utt.common.service.SendEmailService;
import cn.com.utt.common.service.SmsService;
import cn.com.utt.common.vo.RestResult;
import cn.com.utt.common.vo.TableInput;
import cn.com.utt.common.vo.TableOutput;
import cn.com.utt.common.vo.User;
import cn.com.utt.unms.mapper.SmsMarketMapper;
import cn.com.utt.unms.mapper.SmsRecordMapper;
import cn.com.utt.unms.mapper.UserRecordMapper;
import cn.com.utt.unms.pojo.Device;
import cn.com.utt.unms.pojo.SmsMarketing;
import cn.com.utt.unms.pojo.SmsRecord;
import cn.com.utt.unms.pojo.UserRecord;
import cn.com.utt.unms.service.DeviceService;
import cn.com.utt.unms.service.SmsMarketService;
import cn.com.utt.unms.vo.SmsMarketingInfo;
@Service("smsMarketService")
public class SmsMarketServiceImpl implements SmsMarketService{
	@Autowired
	private SmsMarketMapper smsMarketMapper;
	@Autowired
	private DeviceService deviceService;
	@Autowired
	private UserRecordMapper userRecordMapper;
	
	@Autowired 
	private SmsRecordMapper smsRecordMapper;
	@Autowired
	private SmsService smsService;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired 
	private SendEmailService sendEmailService;
	@Value("${noticePhone}")
	private String noticePhone;
	@Value("${noticeEmail}")
	private String noticeEmail;
	@Value("${pageTitle}")
	private String pageTitle;
	
	

	@Override
	public TableOutput<SmsMarketingInfo> querySmsMarketingList(TableInput input, Long userId) {
		Map<String, Object> conditions = new HashMap<>();
		conditions.put("searchs", input.getSearch());
		conditions.put("userId", userId);
		if (input.getOrder() != null) {
			conditions.put("orderColumn", input.getOrder().getColumn());
			conditions.put("orderDirection", input.getOrder().getDir());
		}
		conditions.put("start", input.getStart());
		conditions.put("rows", input.getRows()); 
		
		List<SmsMarketing> smsList=smsMarketMapper.queryByCondition(conditions);
		int total=smsMarketMapper.countByCondition(conditions);
		
		TableOutput<SmsMarketingInfo> output=new TableOutput<>();
		List<SmsMarketingInfo> smsMarketingInfoList=new ArrayList<>();
		for (SmsMarketing smsMarketing : smsList) {
			String str = "";
			if(smsMarketing.getMethod()==0){
				str = "最近临时访问";
			}else{
				str = "自定义";
			}				
			SmsMarketingInfo smv = new SmsMarketingInfo();			
			smv.setId(smsMarketing.getId());
			smv.setTitle(smsMarketing.getTitle());			
			smv.setNum(smsMarketing.getNum());
			smv.setStatus(smsMarketing.getStatus());
			smv.setMethod(str);
			smv.setRemark(smsMarketing.getRemark());
			smv.setCreateTime(smsMarketing.getCreateTime());
			smv.setContext(smsMarketing.getContext());
			smsMarketingInfoList.add(smv);
		}
		output.setList(smsMarketingInfoList);
		output.setTotal(total);
		output.setRows(input.getRows());
		output.setStart(input.getStart());
		return output;
	}

	@Override
	public RestResult loadSmsMarketing(Long userId,Long groupId) {
		RestResult result=new RestResult();
		User user=userMapper.queryById(userId);
		int smsVolume=user.getSmsVolume();
//		SmsMarketing smsMarket=smsMarketMapper.querySmsMarketByUserId(userId);
		result.put("smsvolume", smsVolume);//目前账户剩余短信数量
		result.put("smssign", "上海艾泰科技");//公司签名,新建时默认为上海艾泰科技
		//查询出当前账号下所有的wifi用户，统计上次登录时间大于时间差的
		List<Device> devices = deviceService.queryChildrenDevicesByGroupId(groupId);
		int memebernum=0;
		if (devices.size() > 0) {// 没有查到设备
			long[] deviceIds = new long[devices.size()];
			String[] sns = new String[devices.size()];
			List<String> sns1 = new ArrayList<>();
			for (int i = 0; i < devices.size(); i++) {
				deviceIds[i] = devices.get(i).getId();
				sns[i] = devices.get(i).getSn();
				sns1.add(devices.get(i).getSn());
			}
			long time = 7776000000l;
			Timestamp startTime = new Timestamp(System.currentTimeMillis()- time);
			//按照sn查询用户
			memebernum=userRecordMapper.countBySn(sns1,formatDate(startTime));
		}
		result.put("memebernum", memebernum);//使用手机登录本地WiFi客户数
		System.out.println(result.toJsonObject());
//		result.setErrorCode(1);//0，正常，1异常
//		result.setErrorMsg("发生异常");
		return result;
	}
	public String formatDate(Object stamp){
		DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");   
		return sdf.format(stamp);
	}
	//
	public List<String> getSns(Long userId,Long groupId){
		List<Device> devices = deviceService.queryChildrenDevicesByGroupId(groupId);
		List<String> sns1 = new ArrayList<>();
		if (devices.size() > 0) {// 没有查到设备
			long[] deviceIds = new long[devices.size()];
			String[] sns = new String[devices.size()];
			
			for (int i = 0; i < devices.size(); i++) {
				deviceIds[i] = devices.get(i).getId();
				sns[i] = devices.get(i).getSn();
				sns1.add(devices.get(i).getSn());
			}
//			//按照sn查询用户
//			userRecordMapper.queryUserRecordBySn(sns1);
		}
		return sns1;
	}

	@Override
	public RestResult addSmsMarketing(String userids,SmsMarketing smsMarketing,Long userId) {
		RestResult res=new RestResult();
		User user=userMapper.queryById(userId);
		smsMarketing.setCreateTime(new Timestamp(System.currentTimeMillis()));
		//0 审核中 1 审核未通过 2 待发送 3 发送中 4 发送完成 5 发送失败
		smsMarketing.setStatus((byte)0);
		smsMarketing.setRemark("");
		smsMarketing.setUserId(user.getId());
		List<String> sns=getSns(user.getId(), user.getGroupId());
		System.out.println(sns);
		int smsnum = smsMarketing.getNum();//已发送条数
		int remainSMS = user.getSmsVolume() - smsnum;//剩余条数
		if (remainSMS >= 0) {
			user.setSmsVolume(user.getSmsVolume() - smsnum);
			userMapper.update(user);
			smsMarketMapper.addSmsMarketing(smsMarketing);
			long id = 1l;
			if (smsMarketing.getMethod() == 1) {// 自定义访客
				if (!userids.equals("")) {
					UserRecord ur=null;
					System.out.println(userids.indexOf(','));
					if (userids.indexOf(',') != -1) {
						String[] ids = userids.split(",");
						System.out.println(ids);
						for (String str : ids) {
							if (!str.equals("")) {
								id = Long.parseLong(str);
								if(sns!=null&&sns.size()>0){
									ur=userRecordMapper.queryUserRecordById(sns,id);
								}
								
								if (ur != null) {
									SmsRecord sr = new SmsRecord();
									sr.setMarketingId(smsMarketing.getId());
									if (smsMarketing.getContext().length() > 65) {
										sr.setNum((byte) 2);
									} else {
										sr.setNum((byte) 1);
									}
									sr.setPhone(ur.getUsername());
									sr.setStatus((byte) 0);
									sr.setSendTime(new Timestamp(System.currentTimeMillis()));
									smsRecordMapper.addSmsRecord(sr);
								}
							}
						}
					} else {
						if (!userids.equals("")) {
							id = Long.parseLong(userids);
//							mr = memberRecordDao.queryMemberRecordbyid(id,smsMarketing.getShopId());
							if(sns!=null&&sns.size()>0){
								ur=userRecordMapper.queryUserRecordById(sns,id);
							}
							if (ur != null) {
								SmsRecord sr = new SmsRecord();
								sr.setMarketingId(smsMarketing.getId());
								if (smsMarketing.getContext().length() > 65) {
									sr.setNum((byte) 2);
								} else {
									sr.setNum((byte) 1);
								}
								sr.setPhone(ur.getUsername());
								sr.setStatus((byte) 0);
								smsRecordMapper.addSmsRecord(sr);
							}
						}
					}
				}
			} else {// 最近到访客户
				long time = 7776000000l;
				Timestamp logintime = new Timestamp(System.currentTimeMillis() - time);
				List<UserRecord> list=null;
				if(sns.size()>0){
					list= userRecordMapper.queryBySn(sns, formatDate(logintime));
				}
				int smsnum1 = smsMarketing.getNum();
				int sendpoplenum = 0;// 发送人数
				if (smsMarketing.getContext().length() > 65) {
					sendpoplenum = smsnum1 / 2;// 短信内容超过两条 发送人数减半
				} else {
					sendpoplenum = smsnum1;
				}
				int i = 1;
				if (list != null) {
					for (UserRecord mr1 : list) {
						if (i > sendpoplenum) {
							break;
						}
						SmsRecord sr = new SmsRecord();
						sr.setMarketingId(smsMarketing.getId());
						if (smsMarketing.getContext().length() > 65) {
							sr.setNum((byte) 2);
						} else {
							sr.setNum((byte) 1);
						}
						sr.setPhone(mr1.getUsername());
						sr.setStatus((byte) 0);
						smsRecordMapper.addSmsRecord(sr);
						i++;
					}
				}
			}
			// 以邮件和短信通知管理员，有短信需要审核
			String content = "您有一条来自用户 " + user.getUsername()+ " 的营销短信需要审核，短信标题为：" + smsMarketing.getTitle()+ "【"+pageTitle+"】";
			String jsonContent = "{\"username\":\"" + user.getUsername() + "\",\"pageTitle\":\"" + smsMarketing.getTitle() + "\"}";
			smsService.sendSmsResponse(noticePhone, "SMS_150740414",jsonContent,"艾泰科技");
			sendEmailService.sendEmail(noticeEmail,"营销短信审核通知", content);
		}else{
			res.setErrorCode(1);
			res.setErrorMsg("剩余短信条数不足，请及时充值！");
		}
		return res;
		
	}


	@Override
	public TableOutput<UserRecord> queryRecentUserByCondition(TableInput input, Long userId, Long userGroupId) {
		List<String> sns=getSns(userId, userGroupId);
		long time = 7776000000l;
		Timestamp logintime = new Timestamp(System.currentTimeMillis() - time);
		List<UserRecord> list=new ArrayList<>();
		int total=0;
		if(sns.size()>0){
			list = userRecordMapper.queryBySn(sns, formatDate(logintime));
			total=userRecordMapper.countBySn(sns, formatDate(logintime));
		}
		TableOutput<UserRecord> output=new TableOutput<>();
		output.setList(list);
		output.setTotal(total);
		output.setRows(input.getRows());
		output.setStart(input.getStart());
		return output;
	}

	@Override
	public RestResult editSmsInfo(String title, String content, Long id,Long userId) {
		RestResult res=new RestResult();
		User user=userMapper.queryById(userId);
		SmsMarketing sms=smsMarketMapper.querySmsMarketById(id);
		if(sms!=null){
			int oldContentlength=sms.getContext().length();
			int newContentlength =content.length();
			int oldnum = sms.getNum();//已发送条数
			int newnum = 0;
			int smsvolum=user.getSmsVolume();
			if(sms.getStatus()==0||sms.getStatus()==1){
				if(sms.getStatus()==0){
					if(oldContentlength <= 65 && newContentlength > 65){
						newnum = oldnum * 2;
						smsvolum -=oldnum;
					}else if(oldContentlength > 65 && newContentlength <= 65){
						newnum = oldnum/2;
						smsvolum +=oldnum/2;
					}else{
						newnum = oldnum;
					}
				}else{
					if(oldContentlength <= 65 && newContentlength > 65){
						newnum = oldnum * 2;
					}else if(oldContentlength > 65 && newContentlength <= 65){
						newnum = oldnum/2;
					}else{
						newnum = oldnum;
					}
					smsvolum -= newnum;
				}
				if(smsvolum < 0){
					res.setErrorCode(1);
					res.setErrorMsg("发送条数大于短信剩余容量");
					return res;
				}else{
					sms.setNum(newnum);
					sms.setTitle(title);
					sms.setContext(content);
					sms.setStatus((byte)0);
					sms.setRemark("");

					byte smsnum = 1;
					if(newContentlength>65){
						smsnum =2 ;
					}
					List<SmsRecord> mrs = smsRecordMapper.querySmsRecordByMarketingId(id);
					for(SmsRecord smsRecord:mrs){
						smsRecord.setNum(smsnum);
						//短信编辑后重新回到审核状态
						smsRecord.setStatus((byte)0);
						smsRecordMapper.updateSmsRecord(smsRecord);
					}
					smsMarketMapper.updateSmsMarketing(sms);
					user.setSmsVolume(smsvolum);
					userMapper.update(user);
					res.setErrorMsg("保存成功");
					return res;
				}
			}else{
				res.setErrorCode(1);
				res.setErrorMsg("不可修改");
				return res;
			}
		}else{
			res.setErrorCode(1);
			res.setErrorMsg("记录不存在");
			return res;
		}
	}

	@Override
	public RestResult delSmsInfo(List<Long> id,User users) {
		RestResult res=new RestResult();
		List<SmsMarketing> sms=smsMarketMapper.querySmsMarketByIds(id);
		if(sms!=null&&sms.size()>0){
			List<Byte> status=new ArrayList<>();
			List<Long> smsId=new ArrayList<>();
			for (SmsMarketing smsMarketing : sms) {
				if(smsMarketing.getStatus()==(byte)1||smsMarketing.getStatus()==(byte)0){
					status.add(smsMarketing.getStatus());
					smsId.add(smsMarketing.getId());
				}
			}
			if(sms.size()==status.size()){
				List<Long> list = smsRecordMapper.querySmsRecordByMarketingIds(smsId);
				if(list.size()>0){
					smsRecordMapper.delSmsRecordByIds(list);
				}
				smsMarketMapper.deleteSmsmarketByIds(id);
				// 如果是从审核不通过状态删除，则不需要再次退回短信容量。
				// 只有直接待审核状态直接删除才会直接退回短信容量。
				User user=userMapper.queryById(users.getId());
				for(SmsMarketing smsMarketing : sms){
					if (smsMarketing.getStatus() == (byte)0) {//待审核状态
						int num = smsMarketing.getNum();
						user.setSmsVolume((user.getSmsVolume() + num));
						userMapper.update(user);
//						smsMarketMapper.updateSmsMarketing(smsMarketing);
					}
				}
				res.setErrorMsg("删除成功");
				return res;
			}else{
				res.setErrorCode(1);
				res.setErrorMsg("所选项中包含不可删除的记录");
				return res;
			}
		}
		res.setErrorCode(1);
		res.setErrorMsg("记录不存在");
		return res;
	}

}
